package com.qh.resourcehub.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    public static void main(String[] args) {
        String s = dateFormat("2022-08-16 00:00:00");
        String wordTime = getWordTime("2022-08-18 15:00:00", -8);
        System.out.println(wordTime);

//        System.out.println(s);
    }

    //2022-08-16 00:00 ->20211208
    public static String dateFormat(String time) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMdd");
        String format = null;
        try {
            Date parse = simpleDateFormat.parse(time);
            format = simpleDateFormat2.format(parse);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return format;
    }

    //北京时转世界时
    public static String getWordTime(String time, int hour) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = null;
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(sdf.parse(time));
            c.add(Calendar.HOUR_OF_DAY, hour);
            format = sdf.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("时间转换失败");
        }
        return format;
    }

    //获取时间差
    public static long getTimeDiff(String startTime, String endTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long minutes = 0;
        try {
            Date d1 = df.parse("2004-03-26 13:31");
            Date d2 = df.parse("2004-03-26 13:35");
            minutes = (((d2.getTime() - d1.getTime()) / 1000) / 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return minutes;
    }

    //获取前一天的时间
    public static String getBeforTime(String d_time) {
        Calendar calendar = Calendar.getInstance(); //创建Calendar 的实例
        Date d1=null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd 00:00");
        try {
            d1 = df.parse(d_time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(d1);
        calendar.add(Calendar.DATE,-1);
        Date time = calendar.getTime();
        String format = df2.format(time);
        return format;
    }

}
